package com.baijiayun.live.ui.scanner

import android.graphics.Bitmap
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import com.baijiayun.live.ui.R
import com.baijiayun.live.ui.base.BaseDialogFragment
import com.baijiayun.livecore.utils.LPRxUtils
import com.baijiayun.liveuibase.utils.DisplayUtils
import com.baijiayun.liveuibase.utils.ThemeDataUtil
import com.baijiayun.liveuibase.utils.drawable.DrawableBuilder
import com.baijiayun.liveuibase.zxing.ZxingUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.bjy_qrcode_dialog.*

/**
 * Created by pengwenjian on 2020/11/17
 * Describe:
 */
class QRcodeDialog : BaseDialogFragment() {
    private var qrCodeDispose: Disposable? = null
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        hideTitleBar()
        val url = arguments?.getString("url")
        if (url != null) {
            val width = view.resources.getDimensionPixelSize(R.dimen.bjy_base_ascamera_qrcode_size)
            qrCodeDispose = Observable.create<Bitmap> {
                ZxingUtils.generateQRCodeBitmap(url, width, width)?.run {
                    it.onNext(this) }}
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        ivQRcode.setImageBitmap(it)
                    }
        }
        ivClose.setOnClickListener {
            dismiss()
        }
    }

    override fun onStart() {
        super.onStart()
        dialog?.setCanceledOnTouchOutside(false)
        dialog?.window?.setBackgroundDrawable(DrawableBuilder()
                .rectangle()
                .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_bg_color))
                .cornerRadius(DisplayUtils.dip2px(context!!, 4f))
                .build())
    }

    override fun getLayoutId(): Int {
        return R.layout.bjy_qrcode_dialog
    }

    override fun setWindowParams(windowParams: WindowManager.LayoutParams) {
        super.setWindowParams(windowParams)
        windowParams.width = resources.getDimensionPixelSize(R.dimen.bjy_base_zxing_qrcode_container_width)
        windowParams.height = resources.getDimensionPixelSize(R.dimen.bjy_base_zxing_qrcode_container_height)
        windowParams.gravity = Gravity.CENTER
    }

    override fun hasWindowAnim() = false

    override fun init(savedInstanceState: Bundle?, arguments: Bundle?) {
        // do nothing
    }

    override fun onDestroyView() {
        super.onDestroyView()
        LPRxUtils.dispose(qrCodeDispose)
    }
}